from ast import Num
from datetime import datetime, timedelta
from logging import info
import math
import dbutils
from django.http import JsonResponse
from django.core.cache import cache
from app.static import APPID, APPSERCRET, WX_LOGIN_URL, WX_GET_PHONE_URL
from app.views.common import getWxAccessToken
from app.views.annotate import (
    JsonResponse_res,
    checkParams,
    errorHandling,
    checkLoginHandling,
)
import json
import requests
import uuid

from app.views.DBUtils import DBUtil
from ..common import HttpError, HttpPage, HttpSuccess, upload
from django.core.paginator import Paginator
from django.db import connection
from django.db.models import OuterRef


def handletime(time):
    app_time = ""
    one_day_ago = datetime.now() - timedelta(days=1)
    if time.timestamp() < one_day_ago.timestamp():
        app_time = time.strftime("%Y-%m-%d")
    else:
        count = datetime.now().timestamp() - time.timestamp()
        app_time = f"""{math.floor(count/60/60)}小时前"""
    return app_time


##发表贴子
@checkLoginHandling
@checkParams(["like_status", "id"])
def likeOrForum(request):
    json_data = json.loads(request.body)
    like_status = json_data.get("like_status")
    id = json_data.get("id")
    token = request.META.get("HTTP_X_TOKEN")
    openid = cache.get(token)
    select_sql = f"""select * from discuss where id = {id}"""
    _, result = DBUtil.execute_select(select_sql)
    if len(result) == 0:
        raise HttpError(msg="找不到该贴子")

    discussInfo = result[0]
    suport_user = json.loads(discussInfo["suport_user"])
    if like_status == "1":
        if openid not in suport_user:
            suport_user.append(openid)
    else:
        if openid in suport_user:
            suport_user.remove(openid)
    json_str = json.dumps(suport_user)
    update_sql = f"""update discuss set suport_user = '{json_str}'"""
    DBUtil.execute_insert_or_update(update_sql)
    return HttpSuccess(msg="操作成功")


##发表贴子
@checkLoginHandling
def addForum(request):
    json_data = json.loads(request.body)
    content = json_data.get("content")
    type = json_data.get("type")
    token = request.META.get("HTTP_X_TOKEN")
    openid = cache.get(token)
    insert_sql = f"insert into discuss(openid,content,type)values('{openid}','{content}','{type}')"
    DBUtil.execute_insert_or_update(insert_sql)
    return HttpSuccess(msg="增加成功")


##获取帖子列表
@checkLoginHandling
def getForumList(request):
    json_data = json.loads(request.body)
    pageSize = json_data.get("pageSize", 20)
    currentPage = json_data.get("currentPage", 1)
    openid = None
    if json_data.get("openid"):
        openid = json_data.get("openid")
    sql = """SELECT d.content,d.discuss_index,u.nick_name,d.suport_count,u.img_url,d.suport_user,d.id,d.create_time,u.openid
                       FROM discuss d left JOIN user u ON d.openid = u.openid
                       where d.discuss_index = 0"""
    if openid:
        sql = sql + f""" and u.openid = '{openid}'"""
    _, result = DBUtil.execute_select(sql)
    paginator = Paginator(result, pageSize)
    totalPage = paginator.num_pages
    current_data = paginator.get_page(currentPage)
    for item in current_data.object_list:
        item["suport_user"] =json.loads(item["suport_user"])
        item["create_time"] = handletime(item["create_time"])
    return HttpSuccess(data=HttpPage(current_data.object_list, totalPage))


##发表评论
@checkLoginHandling
@checkParams(["id", "discuss_index"])
def addComment(request):
    json_data = json.loads(request.body)
    content = json_data.get("content", "")
    id = json_data.get("id")
    sub_index = json_data.get("sub_index")
    discuss_index = json_data.get("discuss_index")
    sub_openid = json_data.get("sub_openid")
    token = request.META.get("HTTP_X_TOKEN")
    openid = cache.get(token)
    if discuss_index < 2:
        discuss_index = discuss_index + 1
    insert_sql = f"insert into discuss(openid,content,parent_index,discuss_index,sub_index,sub_openid)values({openid},{content},{id},{discuss_index},{sub_index},{sub_openid})"
    DBUtil.execute_insert_or_update(insert_sql)
    return HttpSuccess(msg="评论成功")


##获取评论详情
@checkLoginHandling
@checkParams(["id"])
def getCommentDetail(request):
    json_data = json.loads(request.body)
    id = json_data.get("id")
    sql_search_info = f""" select *            
        from  discuss d left join  user u on d.openid = u.openid
        where d.id = {id} """
    _, info = DBUtil.execute_select(sql_search_info)
    sql = f""" select *            
        from  discuss d left join  user u on d.openid = u.openid
        where d.parent_index = {id} """
    _, all_discuss = DBUtil.execute_select(sql)
    index = 1
    getChildren(all_discuss, index)
    info[0]["children_list"] = all_discuss
    return HttpSuccess(data = info[0])


def getChildren(list_p, index):
    for item in list_p:
        sql = f""" select *            
            from  discuss d left join  user u on d.openid = u.openid
            where d.parent_index = {item['id']}"""
        _, children_list = DBUtil.execute_select(sql)
        for children in children_list:
            children["create_time"] = handletime(children["create_time"])
            if children["sub_openid"] != None:
                def filter_fn(item):
                    return item["openid"] == children["sub_openid"]
                chose_item = list(filter(filter_fn, children_list))[0]
                children["sub_nick_name"] = chose_item["nick_name"]
                children["sub_img_url"] = chose_item["img_url"]
            item["children_list"] = children_list
            if len(children_list) > 0:
                index += 1
                getChildren(children_list, index)
